<template>
    <div>
        <div class="search-term">
            <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
                <el-form-item>
                    <el-input
                            placeholder="请输入学生姓名"
                            v-model="searchInfo.studentName"
                            clearable
                            size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item v-if="currentRoleId===1||currentRoleId===2">
                    <el-input
                            placeholder="请输入学校名称"
                            v-model="searchInfo.schoolName"
                            clearable
                            size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select
                            v-model="searchInfo.gradeYear"
                            placeholder="请选择年级"
                            clearable
                            size="mini"
                    >
                        <el-option
                                v-for="item in gradeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-input
                            placeholder="请输入原始班级"
                            v-model="searchInfo.gradeClass"
                            clearable
                            size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item v-if="currentRoleId===1||currentRoleId===2">
                    <el-input
                            placeholder="请输入课程班级"
                            v-model="searchInfo.className"
                            clearable
                            size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="onSubmit" type="primary" size="mini"
                    >搜 索
                    </el-button
                    >
                </el-form-item>
                <el-form-item>
                    <el-button @click="openDialog('add')" size="mini" v-if="btns&&btns.includes('add')">新 增</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button @click="importInfo()" size="mini" v-if="btns&&btns.includes('add')">导 入</el-button>
                </el-form-item>
                <el-form-item v-if="currentRoleId===1||currentRoleId===2">
                    <el-button @click="exportStudentClass()" size="mini"
                               v-if="btns&&btns.includes('exportStudentClass')">导出学生报名表
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-table :data="tableData" border>
            <el-table-column prop="schoolName" label="学校名称" align="center" v-if="currentRoleId===1||currentRoleId===2">
            </el-table-column>
            <el-table-column prop="name" label="姓名" align="center">
            </el-table-column>
            <el-table-column prop="sex" label="性别" align="center">
                <template slot-scope="scope">
          <span>{{
            scope.row.sex == 1 ? "男" : "女"
          }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="birthday" label="出生日期" align="center">
            </el-table-column>
            <el-table-column prop="gradeYear" label="年级" align="center">
                <template slot-scope="scope">
                    <span>{{filterGrade(scope.row.gradeYear)}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="gradeClass" label="原始班级" align="center">
            </el-table-column>
            <el-table-column prop="guardianMobile" label="家长电话" align="center">
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="400px">
                <template slot-scope="scope">
                    <el-button
                            @click="editArea(scope.row)"
                            size="mini"
                            type="primary"
                            icon="el-icon-edit"
                            v-if="btns&&btns.includes('edit')"
                    >编辑
                    </el-button
                    >
                    <el-button
                            @click="deleteAreas(scope.row)"
                            size="mini"
                            type="danger"
                            icon="el-icon-delete"
                            v-if="btns&&btns.includes('delete')"
                    >删除
                    </el-button
                    >
                    <el-button
                            @click="studentSignUpDetail(scope.row)"
                            size="mini"
                            type="success"
                            icon="el-icon-view"
                            v-if="btns&&btns.includes('studentSignUpDetail')"
                    >报名情况
                    </el-button
                    >
                    <el-button
                            @click="signInCourse(scope.row)"
                            size="mini"
                            type="primary"
                            icon="el-icon-s-open"
                            v-if="btns&&btns.includes('signInCourse')"
                    >报名课程
                    </el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                :current-page="currPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 30, 50, 100]"
                :style="{ float: 'right', padding: '20px' }"
                :total="totalCount"
                @current-change="handlepageChange"
                @size-change="handleSizeChange"
                layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>


        <!--学生导入-->
        <el-dialog
                :before-close="closeImportDialog"
                title="学生导入"
                :visible.sync="dialogImportVisible"
                class="dialogs"
                width="380px"
        >
            <div style="float: left">
                <el-upload
                        class="upload-demo"
                        :action="`${path}/api-user/student/import`"
                        :limit="1"
                        :on-exceed="handleExceed"
                        :before-upload="checkFile"
                        :on-error="uploadError"
                        :on-success="uploadSuccess"
                        :headers="{ Authorization: token,clientType: 'webApp' }"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove">
                    <el-button size="small" type="primary">选择导入文件</el-button>
                </el-upload>
            </div>
            <div style="float: left;margin-top: 8px; margin-left: 8px;">
                <el-link href="https://istudy-prod.oss-cn-hangzhou.aliyuncs.com/excel/template/学生导入.xlsx">下载模板<i
                        class="el-icon-download el-icon--right"></i>
                </el-link>
            </div>
            <div style="clear: left;margin-top: 20px;text-align: center;" slot="footer">
                <el-button @click="closeImportDialog" size="small">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog
                :before-close="closeDialog"
                :title="dialogTitle"
                :visible.sync="dialogFormVisible"
                class="dialogs"
        >
            <el-form
                    :model="form"
                    :inline="true"
                    :rules="rules"
                    label-width="80px"
                    ref="areaForm"
            >
                <el-form-item label="姓名" prop="name">
                    <el-input
                            autocomplete="off"
                            v-model="form.name"
                            size="small"
                            placeholder="请输入姓名"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="form.sex">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="出生日期" prop="birthday">
                    <el-date-picker
                            size="small"
                            v-model="form.birthday"
                            value-format="yyyy-MM-dd"
                            type="date"
                            placeholder="请选择出生日期"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="年级" prop="gradeYear">
                    <el-select
                            v-model="form.gradeYear"
                            placeholder="请选择年级"
                            size="small"
                            clearable
                    >
                        <el-option
                                v-for="item in gradeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="原始班级" prop="gradeClass">
                    <el-input
                            autocomplete="off"
                            v-model="form.gradeClass"
                            size="small"
                            placeholder="请输入班级"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-form-item label="家长电话" prop="guardianMobile">
                    <el-input
                            autocomplete="off"
                            v-model="form.guardianMobile"
                            size="small"
                            placeholder="请输入手机号"
                            clearable
                    ></el-input>
                </el-form-item>
            </el-form>
            <div class="dialog-footer" slot="footer">
                <el-button @click="closeDialog" size="small">取 消</el-button>
                <el-button @click="enterDialog" type="primary" size="small"
                >确 定
                </el-button
                >
            </div>
        </el-dialog>

        <!--报名情况弹框内容-->
        <el-dialog
                :before-close="closeSignUpDialog"
                :title="studentSignUpTitle"
                :visible.sync="studentSignUpVisible"
                class="studentSignUpDialog"
        >
            <el-table :data="registrationTableData" style="width: 100%;margin-bottom: 10px;" border>
                <el-table-column prop="className" label="班级名称" align="center">
                </el-table-column>
                <el-table-column prop="courseName" label="课程名称" align="center">
                </el-table-column>
                <el-table-column prop="courseTime" label="上课时间" align="center">
                </el-table-column>
                <el-table-column prop="createTime" label="报名时间" align="center">
                </el-table-column>
                <el-table-column prop="orderStatus" label="状态" align="center">
                    <template slot-scope="scope">
                        <span>{{filterRegistrationStatus(scope.row.orderStatus)}}</span>
                    </template>
                </el-table-column>

            </el-table>
            <el-pagination
                    :current-page="registrationCurrPage"
                    :page-size="registrationPageSize"
                    :page-sizes="[10, 20, 30, 50, 100]"
                    :style="{ float: 'right', padding: '20px' }"
                    :total="registrationTotalCount"
                    @current-change="registrationHandlepageChange"
                    @size-change="registrationHandleSizeChange"
                    layout="total, sizes, prev, pager, next, jumper"
            ></el-pagination>
        </el-dialog>

        <!--报名课程弹出框-->
        <el-dialog
                :before-close="signInCourseDialog"
                title="请选择课程"
                :visible.sync="signInCourseDialogVisible"
                width="400px"
        >
            <el-form
                    :model="signInCourseForm"
                    :inline="true"
                    ref="signInCourseForm"
            >
                <el-form-item label="班级" prop="classId">
                    <el-select v-model="signInCourseForm.classId" value-key="signInCourseForm.classId"
                               placeholder="请选择班级" size="small" clearable>
                        <el-option
                                v-for="item in simpleClassOptions"
                                :key="item.classId"
                                :label="item.className"
                                :value="item.classId"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="">
                    <el-button @click="doSignInCourse" type="primary" size="mini">确 定</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

    </div>
</template>

<script>
    // 获取列表内容封装在mixins内部  getTableData方法 初始化已封装完成 条件搜索时候 请把条件安好后台定制的结构体字段 放到 this.searchInfo 中即可实现条件搜索
    import {mapGetters} from "vuex";
    import {addStudent, deleteStudent, editStudent, enableStudent, studentDetail, studentList} from "@/api/student";
    import infoList from "@/components/mixins/infoList";
    import {studentSignUp, createOrderByBack} from "@/api/order";
    import {gradeSimpleList} from "@/api/grade";

    export default {
        name: "Area",
        mixins: [infoList],
        data() {
            return {
                currentRoleId: 0,
                studentSignUpTitle: '',
                studentSignUpVisible: false,
                dialogImportVisible: false,
                signInCourseDialogVisible: false,
                btns: [],
                path: process.env.VUE_APP_BASE_API,
                simpleClassOptions: [],
                statusOptions: [
                    {
                        value: 0,
                        label: "否",
                    },
                    {
                        value: 1,
                        label: "是",
                    },
                ],
                gradeOptions: [
                    {
                        value: 1,
                        label: "一年级",
                    },
                    {
                        value: 2,
                        label: "二年级",
                    },
                    {
                        value: 3,
                        label: "三年级",
                    },
                    {
                        value: 4,
                        label: "四年级",
                    },
                    {
                        value: 5,
                        label: "五年级",
                    },
                    {
                        value: 6,
                        label: "六年级",
                    },
                ],
                roleOptions: [
                    {
                        value: 0,
                        label: "机构",
                    },
                    {
                        value: 1,
                        label: "学校",
                    },
                    {
                        value: 2,
                        label: "教育局",
                    },
                    {
                        value: 3,
                        label: "管理员",
                    },
                ],
                listApi: studentList,
                dialogFormVisible: false,
                dialogTitle: "新增学生",
                form: {},
                signInCourseForm: {studentId: 0,},
                type: "",
                registrationCurrPage: 1,
                registrationTotalCount: 0,
                registrationPageSize: 10,
                registrationTableData: [],
                rules: {
                    name: [
                        {required: true, message: "请输入账户名称", trigger: "blur"},
                    ],
                    sex: [
                        {required: true, message: "请输入账户名称", trigger: "blur"},
                    ],
                    birthday: [{required: true, message: "请选择出生日期", trigger: "change"}],
                    gradeYear: [{required: true, message: "请选择年级", trigger: "change"}],
                    gradeClass: [{required: true, message: "请选择年级", trigger: "change"}],
                    areaName: [
                        {required: true, message: "请选择区域", trigger: "change"},
                    ],
                    enabled: [
                        {required: true, message: "请选择启用", trigger: "change"},
                    ]
                },
            };
        },
        computed: {
            ...mapGetters("user", ["userInfo", "token"]),
        },
        methods: {
            filterRegistrationStatus(val) {
                switch (val) {
                    case 0:
                        return '待付款';
                    case 1:
                        return '已付款';
                    case 2:
                        return '已开班';
                    case 3:
                        return '已退款';
                    case 4:
                        return '已取消';
                    default:
                        break;
                }
            },
            registrationHandleSizeChange(val) {
                this.registrationPageSize = val
                this.getRegistrationTableData()
            },
            registrationHandlepageChange(val) {
                this.registrationCurrPage = val
                this.getRegistrationTableData()
            },
            async studentSignUpDetail(row) {
                this.studentId = row.studentId;
                this.studentSignUpTitle = row.name + "报名情况";
                this.getRegistrationTableData();
                this.studentSignUpVisible = true;
            },
            async getRegistrationTableData(currPage = this.registrationCurrPage, pageSize = this.registrationPageSize) {
                const registrationTable = await studentSignUp({
                    "currPage": currPage,
                    "pageSize": pageSize,
                    "studentId": this.studentId
                })
                this.registrationTableData = registrationTable.data.data
                this.registrationTotalCount = registrationTable.data.totalCount
                this.registrationCurrPage = registrationTable.data.currPage
                this.registrationPageSize = registrationTable.data.pageSize
                this.$forceUpdate()

            },
            //报名课程
            async signInCourse(val) {
                this.signInCourseDialogVisible = true;
                const res = await gradeSimpleList({"schoolId": val.schoolId});
                this.simpleClassOptions = res.data
                this.signInCourseForm.studentId = val.studentId
            },
            signInCourseDialog() {
                this.signInCourseDialogVisible = false;
                this.signInCourseForm = {};
            },
            async doSignInCourse() {
                this.$confirm("此操作将学生报名该课程, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(async () => {
                        let
                            {
                                classId, studentId
                            } = this.signInCourseForm;
                        const res = await createOrderByBack({classId, studentId});
                        if (res.statusCode === 0) {
                            this.$message({
                                type: "success",
                                message: "更新成功!",
                            });
                            this.signInCourseDialog();
                            this.getTableData();
                        }
                    })
                    .catch(() => {
                        // this.$message({
                        //     type: "info",
                        //     message: "已取消",
                        // });
                    });
            },
            handleRemove(file, fileList) {
            },
            handlePreview(file) {
            },
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },
            closeImportDialog() {
                this.dialogImportVisible = false;
            },
            closeSignUpDialog() {
                this.studentSignUpVisible = false;
            },
            //导入框
            importInfo() {
                this.dialogImportVisible = true;
            },
            //条件搜索前端看此方法
            onSubmit() {
                this.page = 1;
                this.pageSize = 10;
                this.getTableData();
            },
            initForm() {
                this.$refs.areaForm.resetFields();
                this.form = {
                    path: "",
                    apiGroup: "",
                    method: "",
                    description: "",
                };
            },
            //过滤年级
            filterGrade(val) {
                switch (val) {
                    case 1:
                        return '一年级'
                    case 2:
                        return '二年级'
                    case 3:
                        return '三年级'
                    case 4:
                        return '四年级'
                    case 5:
                        return '五年级'
                    case 6:
                        return '六年级'
                    default:
                        break;
                }
            },
            closeDialog() {
                this.initForm();
                this.dialogFormVisible = false;
            },
            openDialog(type) {
                switch (type) {
                    case "add":
                        this.dialogTitle = "新增学生";
                        break;
                    case "edit":
                        this.dialogTitle = "编辑学生";
                        break;
                    default:
                        break;
                }
                this.type = type;
                this.dialogFormVisible = true;
            },
            async exportStudentClass() {
                let schoolName = this.searchInfo.schoolName;
                if (schoolName === undefined || schoolName === '') {
                    this.$message({
                        type: "warning",
                        message: "请输入学校名称"
                    });
                    return;
                }
                let gradeYear = this.searchInfo.gradeYear;
                if (gradeYear === undefined || gradeYear === '') {
                    this.$message({
                        type: "warning",
                        message: "请输入年级"
                    });
                    return;
                }
                let gradeClass = this.searchInfo.gradeClass;
                if (gradeClass === undefined || gradeClass === '') {
                    this.$message({
                        type: "warning",
                        message: "请输入班级"
                    });
                    return;
                }
                let className = this.searchInfo.className;
                let excelPath = this.path + "api-user/student/class/export?schoolName=" + schoolName + "&gradeYear=" + gradeYear + "&gradeClass=" + gradeClass + "&classId=" + className;
                window.open(excelPath);
            },
            //启用/停用
            async changeEnable(row) {
                const res = await enableStudent(row.studentId)
                if (res.statusCode === 0) {
                    this.$message({
                        type: "success",
                        message: "启用/停用成功",
                        showClose: true,
                    });
                }
                this.getTableData();
            },
            async editArea(row) {
                const res = await studentDetail(row.studentId)
                this.form = res.data;
                // console.log(this.form)
                this.openDialog("edit");
            },
            async deleteAreas(row) {
                this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(async () => {
                        const res = await deleteStudent(row.studentId);
                        if (res.statusCode === 0) {
                            this.$message({
                                type: "success",
                                message: "删除成功!",
                            });
                            this.getTableData();
                        }
                    })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除",
                        });
                    });
            },
            async enterDialog() {
                this.$refs.areaForm.validate(async (valid) => {
                    if (valid) {
                        switch (this.type) {
                            case "add": {
                                const reg = /^1[3456789]\d{9}$/;
                                if (this.form.guardianMobile !== undefined && this.form.guardianMobile !== '') {
                                    if (!reg.test(this.form.guardianMobile)) {
                                        this.$message({
                                            type: "info",
                                            message: "请输入正确的手机号",
                                            showClose: true,
                                        });
                                        return
                                    }
                                }
                                const res = await addStudent(this.form);
                                if (res.statusCode === 0) {
                                    this.$message({
                                        type: "success",
                                        message: "添加成功",
                                        showClose: true,
                                    });
                                }
                                this.getTableData();
                                this.closeDialog();
                            }

                                break;
                            case "edit": {
                                const res = await editStudent(this.form);
                                if (res.statusCode === 0) {
                                    this.$message({
                                        type: "success",
                                        message: "编辑成功",
                                        showClose: true,
                                    });
                                }
                                this.getTableData();
                                this.closeDialog();
                            }
                                break;
                            default: {
                                this.$message({
                                    type: "error",
                                    message: "未知操作",
                                    showClose: true,
                                });
                            }
                                break;
                        }
                    }
                });
            },
            //文件上传
            checkFile(file) {
                const isXls = file.type === "application/vnd.ms-excel";
                const isXlsx = file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isXls && !isXlsx) {
                    this.$message.error("文件格式错误!");
                }
                if (!isLt2M) {
                    this.$message.error("上传文件大小不能超过 2MB!");
                }
                return (isXls || isXlsx) && isLt2M;
            },
            uploadSuccess(res) {
                if (res.statusCode === 0) {
                    this.$message({
                        type: "success",
                        message: "上传成功",
                    });
                    this.dialogImportVisible = false;
                    this.getTableData();
                } else {
                    this.$message({
                        type: "warning",
                        message: res.msg,
                    });
                }
            },
            uploadError() {
                this.$message({
                    type: "error",
                    message: "上传失败",
                });
            },
            // async getSimpleGrade() {
            //     let data = await gradeSimpleList();
            //     this.simpleClassOptions = data.data;
            // }
        },
        created() {
            this.currentRoleId = this.userInfo.roleId;
            // this.getSimpleGrade();
            this.getTableData();
            this.btns = this.$route.meta.btnList
        },
    };
</script>
<style scoped lang="scss">
    .green {
        color: #67c23a;
    }

    .red {
        color: #f56c6c;
    }

    .button-box {
        // padding: 10px 20px;
        .el-button {
            float: right;
        }
    }

    .el-tag--mini {
        margin-left: 5px;
    }

    .dialogs {
        ::v-deep .el-input-group--append .el-input__inner {
            width: 170px !important;
        }

        ::v-deep .el-dialog__body {
            padding: 15px 20px 10px 20px;
        }

        ::v-deep .el-input__inner {
            width: 225px;
        }

        ::v-deep .el-textarea__inner {
            width: 225px;
        }

        .dialog-footer {
            text-align: center;
        }

        ::v-deep .el-input-number .el-input__inner {
            width: 130px;
        }

        ::v-deep .el-form .el-form-item {
            width: 49%;
            margin: 0;
        }

        ::v-deep .el-form .pics {
            width: 100%;
            margin-bottom: 22px;
        }

        ::v-deep .el-form .small_pic {
            .el-upload--picture-card {
                height: 80px;
                width: 80px;
                line-height: 80px;
            }
        }

        .pics {
            ::v-deep .el-form-item__content {
                width: calc(100% - 112px)
            }
        }

        .el-form .pics ::v-deep .el-form-item__content .el-textarea__inner {
            width: 100%;
        }
    }

    .studentSignUpDialog {
        ::v-deep .el-input-group--append .el-input__inner {
            width: 170px !important;
        }

        ::v-deep .el-dialog__body {
            height: 500px;
            padding: 15px 20px 10px 20px;
        }

        ::v-deep .el-textarea__inner {
            width: 225px;
        }

        .dialog-footer {
            text-align: center;
        }

        ::v-deep .el-input-number .el-input__inner {
            width: 130px;
        }

        .item-label {
            ::v-deep .el-form-item__label {
                width: 142px !important;
            }

            ::v-deep .el-input__inner {
                width: 162px !important;
            }

            ::v-deep .el-date-editor.el-input {
                width: 162px !important;
            }
        }

        .item-labels {
            ::v-deep .el-form-item__content {
                width: 225px !important;
            }

            ::v-deep .el-form-item__label {
                width: 80px !important;
            }

            ::v-deep .el-input {
                width: 102px !important;
            }

            ::v-deep .el-input__inner {
                width: 102px !important;
            }

        }

        ::v-deep .el-form .el-divider .el-divider__text {
            font-weight: bold;
            color: #409eff;
        }
    }
</style>
